package com.lz.service;

import com.lz.domain.Task;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;

/**
 * <pre>
 * @描述：
 * @作者：lizhao
 * @创建时间： 2024/12/18 上午9:18
 * </pre>
 **/
public class DockerService {
    public String test(Task task) {
//        String tarFilePath = "/root/jar/mysql-5.7.tar"; // 定义存放镜像的路径
        String tarFilePath = task.getFilePath(); // 定义存放镜像的路径
        String pathEnv = System.getenv("PATH");
        System.out.println("PATH: " + pathEnv);

        // 使用 ProcessBuilder 正确执行 docker load 命令
        ProcessBuilder processBuilder = new ProcessBuilder("docker", "load", "-i", tarFilePath);
        processBuilder.environment().put("PATH", pathEnv);

        try {
            Process process = processBuilder.start();
//                StartDTO dto = logRecode(process, task);
//                startDTO = dto;
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
            int exitCode = process.waitFor();
            System.out.println("Exited with code : " + exitCode);
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }


        // 运行Docker容器
//            String containerName = task.getNo(); // 定义容器名称为编号名称
        String fileName = tarFilePath.substring(tarFilePath.lastIndexOf("/") + 1);

        // 提取不包含扩展名的文件名作为镜像名称
        String imageName = fileName.substring(0, fileName.lastIndexOf("."));
        System.out.println("Image name: " + imageName);
        ProcessBuilder runProcessBuilder = new ProcessBuilder("docker", "run", "-d");
        if (task.getRunParams() != null) {
            List<String> list = (task.getRunParams());
            runProcessBuilder.command().addAll(list);
        }
        runProcessBuilder.command().add(imageName.replace("-", ":"));
        runProcessBuilder.redirectErrorStream(true); // 合并标准输出和错误输出
        try {
            Process runProcess = runProcessBuilder.start();
//                StartDTO dto = logRecode(runProcess, task);
//                startDTO = dto;
            // 读取命令的输出并打印
            BufferedReader reader = new BufferedReader(new InputStreamReader(runProcess.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
            int runExitCode = runProcess.waitFor();
            System.out.println("Container exited with code : " + runExitCode);
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
        return null;
    }

}
